const connection = require('../app/database.js')

class NavService{
	//创建用户
	async saveNav(payload){
		const { name} = payload
		const statement = 'INSERT INTO `nav` (name) VALUES (?);'
		const [result] = await connection.execute(statement, [name])
		return result
	}
	
	async saveNavContent(payload){
		const { name,label,icon,href,navId} = payload
		const statement = 'INSERT INTO `nav_content` (name,label,icon,href,navId) VALUES (?,?,?,?,?);'
		const [result] = await connection.execute(statement, [name,label,icon,href,navId])
		return result
	}
	
	
	async updateNav(payload){
		const { name,id} = payload
		const statement = 'UPDATE nav SET name = ? WHERE id = ?'
		const [result] = await connection.execute(statement, [name,id])
		return result
	}
	
	async updateNavContent(payload){
		const { name,navId,icon,href,label,id} = payload
		const statement = 'UPDATE nav_content SET name = ?,navId = ?,icon = ?,href = ?,label = ? WHERE id = ?'
		const [result] = await connection.execute(statement, [name,navId,icon,href,label,id])
		return result
	}
	
	async deleteNav(id){
		const statement = `DELETE FROM nav WHERE id = ?`
		const [result] = await connection.execute(statement,[id])
		return result
	}
	
	async queryById(id){
		const statement = `SELECT * FROM nav_content WHERE navId = ?`
		const [result] = await connection.execute(statement,[id])
		return result
	}
	
	async deleteNavContent(id){
		const statement = `DELETE FROM nav_content WHERE id = ?`
		const [result] = await connection.execute(statement,[id])
		return result
	}
	
	async queryNavList(){
		const statement = `SELECT * FROM nav`
		const [result] = await connection.execute(statement)
		const content = await Promise.all(result.map(item => connection.execute(`SELECT * FROM nav_content WHERE navId = ?`,[item.id])))
		result.forEach((item,index) => {
			item.children = content[index][0]
		})
		return result
	}
}


module.exports = new NavService()
